package servlet.account.control;

import jakarta.servlet.annotation.WebServlet;
import mysql.JdbcUtil;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@WebServlet("/Logup")
public class Logup extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkSql = "SELECT * FROM accounts WHERE username = ?";
        String insertSql = "INSERT INTO accounts (username, password) VALUES (?, ?)";
        RequestDispatcher dispatcher;

        try {
            JdbcUtil ju = new JdbcUtil(); // 实例化应在方法内部
            Connection conn = ju.connectMySQL();
            // 检查账号是否已存在
            PreparedStatement checkStmt = conn.prepareStatement(checkSql);
            checkStmt.setString(1, username);
            ResultSet rs = checkStmt.executeQuery();
            if (rs.next()) {
                // 账号已存在，设置错误信息
                req.setAttribute("logupError", "账号已存在");
                dispatcher = req.getRequestDispatcher("/chushi/jsp/logup.jsp");
                dispatcher.forward(req, resp);
            } else {
                // 账号不存在，插入新账号
                PreparedStatement insertStmt = conn.prepareStatement(insertSql);
                insertStmt.setString(1, username);
                insertStmt.setString(2, password);
                insertStmt.executeUpdate();

                // 注册成功，自动登录
                req.setAttribute("Login","注册成功");
                req.setAttribute("username", username);
                req.setAttribute("password", password);
                dispatcher = req.getRequestDispatcher("Login");
                dispatcher.forward(req, resp);
            }
            // 关闭资源
            rs.close();
            checkStmt.close();
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 转发到注册页面
        RequestDispatcher dispatcher = req.getRequestDispatcher("/chushi/jsp/logup.jsp");
        dispatcher.forward(req, resp);
    }
}
